package com.mubai.oa.service.impl;

import java.util.*;

import com.mubai.common.constant.OAConstants;
import com.mubai.common.support.Convert;
import com.mubai.common.utils.DateUtils;
import com.mubai.oa.domain.Notify;
import com.mubai.oa.domain.NotifyDto;
import com.mubai.oa.domain.NotifyRecord;
import com.mubai.oa.mapper.NotifyMapper;
import com.mubai.oa.mapper.NotifyRecordMapper;
import com.mubai.oa.service.NotifyService;
import com.mubai.system.domain.SysUser;
import com.mubai.system.mapper.SysUserMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

/**
 * 通知通告 服务层实现
 *
 * @author baichuanping
 * @date 2018-12-18
 */
@Service
public class NotifyServiceImpl implements NotifyService
{
	@Autowired
	private NotifyMapper notifyMapper;
	@Autowired
	private NotifyRecordMapper notifyRecordMapper;

	/**
	 * 查询通知通告信息
	 *
	 * @param id 通知通告ID
	 * @return 通知通告信息
	 */
	@Override
	public Notify selectNotifyById(Long id)
	{
		return notifyMapper.selectNotifyById(id);
	}

	/**
	 * 查询通知通告列表
	 *
	 * @param notify 通知通告信息
	 * @return 通知通告集合
	 */
	@Override
	public List<Notify> selectNotifyList(Notify notify)
	{
		return notifyMapper.selectNotifyList(notify);
	}

	/**
	 * 新增通知通告
	 *
	 * @param notify 通知通告信息
	 * @return 结果
	 */
	@Transactional(rollbackFor = Exception.class)
	@Override
	public int insertNotify(Notify notify)
	{
		int r = notifyMapper.insertNotify(notify);
		// 保存到接收表列表中
		Long notifyId = notify.getId();
		List<NotifyRecord> notifyRecords = new ArrayList<>();
		for (Long userId: notify.getUserIds()){
			NotifyRecord notifyRecord = new NotifyRecord();
			notifyRecord.setNotifyId(notifyId);
			notifyRecord.setUserId(userId);
			notifyRecord.setIsRead(OAConstants.NOTIFY_READ_NO);
			notifyRecords.add(notifyRecord);
		}
		notifyRecordMapper.batchSave(notifyRecords);
		return r;
	}

	/**
	 * 修改通知通告
	 *
	 * @param notify 通知通告信息
	 * @return 结果
	 */
	@Override
	public int updateNotify(Notify notify)
	{
		return notifyMapper.updateNotify(notify);
	}

	/**
	 * 删除通知通告对象
	 *
	 * @param ids 需要删除的数据ID
	 * @return 结果
	 */
	@Override
	public int deleteNotifyByIds(String ids)
	{
		notifyRecordMapper.batchRemoveByNotifbyId(Convert.toStrArray(ids));
		return notifyMapper.deleteNotifyByIds(Convert.toStrArray(ids));
	}

	/**
	 * 获取自己的消息
	 *
	 * @param map
	 * @return
	 */
	@Override
	public List<NotifyDto> selfList(Map<String, Object> map) {
		List<NotifyDto> notifyDtoList = notifyMapper.selectNotifyDtoList(map);
		for (NotifyDto notifyDto : notifyDtoList) {
			notifyDto.setBefore(DateUtils.getTimeBefore(notifyDto.getUpdateTime()));
			notifyDto.setSender(notifyDto.getCreateBy());
		}
		return notifyDtoList;
	}

}